/**
 * 使用方法
 * LogUtil.createSDCardDir("log/AutoDialTest");
 * LogUtil.saveLog2File("保存日志");
 */
package com.ctu.app.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Environment;
import android.util.Log;

/**
 * 该类用于保存日志到sdcard中
 * 
 * @author wxm
 * 
 */
public class LogUtil {

	private static final String TAG = "LogUtil";
	private static SimpleDateFormat formatLog = new SimpleDateFormat(
			"yyyy/MM/dd-HH:mm:ss");// 用于格式化日期,作为日志文件名的一部分
	static String usedFileName;// 正在使用的文件名
	static String usedFilePath;// 文件的路径
	static SimpleDateFormat formatFileName = new SimpleDateFormat("yyyy_MM_dd");
	static String fileName;// 文件名
	static boolean DEBUGX = false;
	static boolean DEBUG1 = false;

	private static File customPath;

	public static void saveLog2File(final String log) {

		Runnable printRunnable = new Runnable() {

			@Override
			public void run() {

				if (DEBUGX) {
					Log.d(TAG, "customPathDebug: " + customPath);

				}

				if (DEBUGX) {
					Log.d(TAG, "usedFilePathDebug: " + usedFilePath);
				}

				// 如果文件不存在，或者如果当前的日期大于之前的日期，就新创建一个文件
				if (usedFilePath == null || compareDate()) {

					usedFileName = formatFileName.format(new Date());

					if (DEBUGX) {
						Log.d(TAG, "customPathDebug: " + customPath);

					}

					usedFilePath = customPath + "/" + usedFileName + ".log";// 文件名

					if (DEBUGX) {
						Log.d(TAG, "创建日志文件====usedFilePath: " + usedFilePath
								+ "," + "usedFileName: " + usedFileName);
					}
				}

				BufferedWriter logWriter = null;
				try {
					if (DEBUGX) {
						Log.d(TAG, "当前使用的文件路径：usedFilePath: " + usedFilePath);
					}
					String time = formatLog.format(new Date());
					logWriter = new BufferedWriter(new OutputStreamWriter(
							new FileOutputStream(usedFilePath, true), "gbk"));
					logWriter.write(time + ": " + log + "\r\n");

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (logWriter != null)
						try {
							logWriter.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
				}
			}
		};

		ExecutorService pool = Executors.newFixedThreadPool(10);// 创建10个线程池
		pool.submit(printRunnable);

	}

	/**
	 * 是否创建新文件
	 * 
	 * @param DATE1
	 * @param DATE2
	 */
	private static boolean compareDate() {
		String newDate = formatFileName.format(new Date());// 新时间
		String oldDate = usedFileName;// 旧的时间
		if (DEBUG1) {
			Log.d(TAG, "newDate: " + newDate + "," + "oldDate: " + oldDate);
		}
		DateFormat df = new SimpleDateFormat("yyyy_MM_dd");
		try {

			Date current = df.parse(newDate);
			Date old = df.parse(oldDate);

			if (current.getTime() > old.getTime()) {
				if (DEBUGX) {
					Log.d(TAG, "重新创建log文件:" + newDate);
				}
				return true;
			} else {// 同一天
				if (DEBUGX) {
					Log.d(TAG, "使用原log文件:" + oldDate);// 使用之前的线程
				}
				return false;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}

	/**
	 * 将异常日志保存到异常文件夹中
	 * 
	 * @param exLogContent
	 *            异常日志内容
	 * @param fileNAME
	 *            //文件名
	 */
	public static void saveExceptionLog2File(final String exLogContent,
			final String fileNAME) {

		Runnable writeExLog = new Runnable() {

			@Override
			public void run() {
				String time = formatLog.format(new Date());
				String fileName = fileNAME + ".log";

				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					File dir = new File(
							Environment.getExternalStorageDirectory() + "/log");
					Log.d(TAG, "dir: " + dir);

					if (!dir.exists()) {
						dir.mkdir();
					}

					String path = dir + "/" + fileName;
					BufferedWriter logWriter = null;
					try {
						logWriter = new BufferedWriter(new OutputStreamWriter(
								new FileOutputStream(path, true), "GBK"));
						logWriter.write(time + ": " + exLogContent + "\r\n");

					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (logWriter != null)
							try {
								logWriter.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
					}

				}

			}
		};
		ExecutorService pool = Executors.newFixedThreadPool(10);// 创建10个线程池
		pool.submit(writeExLog);

	}

	/**
	 * 保存异常信息到文件
	 * 
	 * @param ex
	 * @param fileNAME
	 * @return
	 */
	public static String saveExceptionLog2File(Throwable ex, String fileNAME) {
		StringBuffer sb = new StringBuffer();
		String time = formatLog.format(new Date());

		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		ex.printStackTrace(pw);
		Throwable cause = ex.getCause();

		// 循环着把所有的异常信息写入writer中
		while (cause != null) {
			cause.printStackTrace(pw);
			cause = cause.getCause();
		}

		pw.close();// 记得关闭

		String result = writer.toString();
		sb.append(time + "====" + result);

		String fileName = fileNAME + ".log";

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File dir = new File(Environment.getExternalStorageDirectory()
					+ "/log");
			Log.d(TAG, "异常日志文件: " + dir);
			if (!dir.exists())
				dir.mkdir();

			String path = dir + "/" + fileName;
			BufferedWriter logWriter = null;

			try {
				logWriter = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(path, true), "GBK"));
				logWriter.write(sb.toString() + "\r\n");

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (logWriter != null)
					try {
						logWriter.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}

		}
		return null;
	}

	/**
	 * 在sd卡上创建文件夹
	 * 
	 * @param dir
	 * @return
	 */
	public static void createSDCardDir(String dir) {
		if (DEBUGX) {
			Log.d(TAG, "createSDCardDi@@@@@@@@@@@@@@ ");
		}

		File filePath = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			// 创建一个文件夹对象，赋值为外部存储器的目录
			File sdcardDir = Environment.getExternalStorageDirectory();
			// 得到一个路径，内容是sdcard的文件夹路径和名字
			String path = sdcardDir.getPath() + "/" + dir;
			filePath = new File(path);
			if (!filePath.exists()) {
				// 若不存在，创建目录，可以在应用启动的时候创建
				filePath.mkdirs();// 多层文件夹
				Log.d(TAG, "正在创建目录:filePath= " + filePath);
			} else {
				Log.d(TAG, "目录已存在:filePath=" + filePath);
			}
		}

		customPath = filePath;
	}

}
